Ext.require([
    'Ext.tree.*',
    'Ext.data.*',
    'Ext.tip.*'
]);

Ext.onReady(function(){

	Ext.regModel('Category', {
		fields: [
			{name: 'idCategory', type: 'int'},
			{name: 'name',  type: 'string'}
		]
	});

	function getMemberParams(){
		var b = {
				memberEmail: Ext.util.Cookies.get('memberEmail'),
				memberPassword: Ext.util.Cookies.get('memberPassword')
		};

		return b;
		
	};

	function getAddParams(){
		var idCategory = null;

		var sm = tree.getSelectionModel();
		var s = sm.getSelection();
		if(s && s.length > 0){
			var selectednode = s[0];
			if(!selectednode.isRoot()){
				idCategory = selectednode.get('idCategory');
			}
		}		
		return Ext.merge(getMemberParams(), {idCategory: idCategory});
	}

    var store = Ext.create('Ext.data.TreeStore', {
		model: 'Category',
		autoLoad: true,
		autoSync: true,
        proxy: {
            type: 'ajax',
            url: '../../cattolica-web/category/list',
			extraParams: getMemberParams(),
            reader: {
                type: 'json',
                idProperty: 'idCategory',
				root: 'categories'
            },
			success: function(form, action) {
				tree.expandAll();
			}
        },
		
        nodeParam: 'idCategory',

        sorters: [{
            property: 'name',
            direction: 'ASC'
        }]
    });

    var addPanel = Ext.create('Ext.form.FormPanel', {
		renderTo: 'div_add',
        border:false,
        width: 350,
        fieldDefaults: {
            labelWidth: 75,
            msgTarget: 'side'
        },
        defaults: {
            anchor: '100%'
        },

        items: [{
                xtype: 'textfield',
                fieldLabel: 'Nome',
                anchor: '100%',
                name: 'name',
                allowBlank: false
        }],
                   
        buttons: [{
            text: 'Salva',
            disabled: true,
            formBind: true,
			handler: function() {
				var form = this.up('form').getForm();
				var name = addPanel.getForm().getValues().name;
				var selectednode = tree.getRootNode();

				var sm = tree.getSelectionModel();
				var s = sm.getSelection();
				if(s && s.length > 0){
					selectednode = s[0];
				}

				if(!selectednode){
					Ext.Msg.alert('Warning', 'Please select a category');
					return;
				}

				var child = selectednode.findChildBy(function(node){
					return node.get('name') == name;
				});
				if(child){
					Ext.Msg.alert('Duplicated entry', 'Category already exists');
					return;
				}

				

				if (form.isValid()) {
					form.submit({
						url: '../../cattolica-web/category/add',
						params: getAddParams(),
	                    submitEmptyText: false,
						success: function(form, action) {
							store.load();
						},
						failure: function(form, action) {
							Ext.Msg.alert('Failed', action.response.statusText);
						}
					});
				}
			}
        }]
    });

	var tree = new Ext.tree.TreePanel({
		width: 350,
		height: 600,
		store: store,
		rootVisible: true,        
		renderTo: 'div_main',
		useArrows: true,
		displayField: 'name',

        root: {
			idCategory: null,
            name: 'The town\'s time',
            id: null,
            expanded: true,
			nodeType: 'async'
        },
        dockedItems: [{
            xtype: 'toolbar',
            items: [{
                text: 'Eliminare',
				iconCls: 'icon-delete',
                handler: function(){
					var sm = tree.getSelectionModel();
					var s = sm.getSelection();
					if(s && s.length > 0){
						var selectednode = s[0];
						var idCategory = selectednode.get('idCategory');
						Ext.Ajax.request({
							url: '../../cattolica-web/category/remove',
							params: Ext.merge(getMemberParams(), {idCategory: idCategory}),
							success: function(response){
								store.load();
							},
							failure: function(response) {
								Ext.Msg.alert('Failed', response.statusText);
							}
						});
					}
                }
            }]
        }]
	});

});